package org.telegram.bot.mq.consumer;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.mq.pubsub.AbstractChannelMessageListener;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.telegram.bot.domain.BotChatVerify;
import org.telegram.bot.domain.BotConfigWord;
import org.telegram.bot.domain.BotGroup;
import org.telegram.bot.emums.BotCacheConstants;
import org.telegram.bot.mapper.*;
import org.telegram.bot.mq.message.GroupCacheRefreshMessage;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * GroupCacheRefreshMessage 消费者
 * @Author: wyx
 */
@Component
@Slf4j
public class GroupCacheRefreshConsumer extends AbstractChannelMessageListener<GroupCacheRefreshMessage> {

    @Resource
    private RedisCache redisCache;

    @Resource
    private BotGroupMapper botGroupMapper;

    @Resource
    private BotChatVerifyMapper botChatVerifyMapper;

    @Resource
    private BotConfigWordMapper botConfigWordMapper;

    @Resource
    private BotKeyWordReplyMapper botKeyWordReplyMapper;

    @Resource
    private BotBanEmojiMapper botBanEmojiMapper;

    /**
     * 处理消息
     *
     * @param message 消息
     */
    @Override
    public void onMessage(GroupCacheRefreshMessage message) {
        updateCache(message.getChatIds());
    }

    // 缓存群组信息方法
    @PostConstruct
    @Async
    protected int initCache() {
        try {
            return updateCache(new ArrayList<>());
        } catch (Exception e) {
            log.error("初始化群组缓存失败", e);
            return 0;
        }
    }

    /**
     * 更新缓存群组信息
     * @param ids 群组ID列表，如果为空则更新所有群组
     */
    public int updateCache(List<Long> ids) {
        LambdaQueryWrapper<BotGroup> queryWrapper = new LambdaQueryWrapper<>();
        if (!CollectionUtils.isEmpty(ids)) {
            queryWrapper.in(BotGroup::getChatId, ids);
        }
        List<BotGroup> botGroups = botGroupMapper.selectList(queryWrapper);

        if (botGroups == null || botGroups.isEmpty()) {
            log.warn("没有需要更新的群组信息");
            return 0;
        }

        // 批量查询相关数据
        Map<Long, BotChatVerify> chatVerifyMap = getChatVerifyMap(botGroups);
        Map<Long, BotConfigWord> configWordMap = getConfigWordMap(botGroups);
        Map<Long, Map<String, String>> keyReplyMap = getKeyReplyMap(botGroups);
        Map<Long, Set<String>> banEmojiMap = getBanEmojiMap(botGroups);

        botGroups.forEach(botGroup -> {
            Long chatId = botGroup.getChatId();
            if (chatId != null) {
                botGroup.setChatVerify(chatVerifyMap.get(chatId));
                botGroup.setConfigWord(configWordMap.get(chatId));
                botGroup.setKeyReplyMap(keyReplyMap.get(chatId));
                botGroup.setBanEmojiSet(banEmojiMap.get(chatId));
                redisCache.setCacheObject(BotCacheConstants.BOT_CHAT + chatId, botGroup);
            }
        });

        log.info("更新群组缓存数量：{}, ids: {}", botGroups.size(), botGroups.stream().map(BotGroup::getChatId).collect(Collectors.toList()));
        return botGroups.size();
    }

    /**
     * 获取群组验证信息映射
     * @param botGroups 群组列表
     * @return 群组ID到验证信息的映射
     */
    private Map<Long, BotChatVerify> getChatVerifyMap(List<BotGroup> botGroups) {
        List<Long> chatIds = botGroups.stream().map(BotGroup::getChatId).filter(Objects::nonNull).collect(Collectors.toList());
        if (chatIds.isEmpty()) {
            return Collections.emptyMap();
        }
        return botChatVerifyMapper.selectList(new LambdaQueryWrapper<BotChatVerify>().in(BotChatVerify::getChatId, chatIds))
                .stream()
                .collect(Collectors.toMap(BotChatVerify::getChatId, Function.identity()));
    }

    /**
     * 获取群组配置词汇映射
     * @param botGroups 群组列表
     * @return 群组ID到配置词汇的映射
     */
    private Map<Long, BotConfigWord> getConfigWordMap(List<BotGroup> botGroups) {
        List<Long> chatIds = botGroups.stream().map(BotGroup::getChatId).filter(Objects::nonNull).collect(Collectors.toList());
        if (chatIds.isEmpty()) {
            return Collections.emptyMap();
        }
        return botConfigWordMapper.selectList(new LambdaQueryWrapper<BotConfigWord>().in(BotConfigWord::getChatId, chatIds))
                .stream()
                .collect(Collectors.toMap(BotConfigWord::getChatId, Function.identity()));
    }

    /**
     * 获取群组关键字回复映射
     * @param botGroups 群组列表
     * @return 群组ID到关键字回复映射的映射
     */
    private Map<Long, Map<String, String>> getKeyReplyMap(List<BotGroup> botGroups) {
        List<Long> chatIds = botGroups.stream().map(BotGroup::getChatId).filter(Objects::nonNull).toList();
        if (chatIds.isEmpty()) {
            return Collections.emptyMap();
        }
        return botGroups.stream()
                .collect(Collectors.toMap(
                        BotGroup::getChatId,
                        botGroup -> botKeyWordReplyMapper.getKeyReplyMap(botGroup.getChatId())
                ));
    }

    /**
     * 获取群组禁止表情映射
     * @param botGroups 群组列表
     * @return 群组ID到禁止表情集合的映射
     */
    private Map<Long, Set<String>> getBanEmojiMap(List<BotGroup> botGroups) {
        List<Long> chatIds = botGroups.stream().map(BotGroup::getChatId).filter(Objects::nonNull).toList();
        if (chatIds.isEmpty()) {
            return Collections.emptyMap();
        }
        return botGroups.stream()
                .collect(Collectors.toMap(
                        BotGroup::getChatId,
                        botGroup -> botBanEmojiMapper.emojiList(null)
                ));
    }
}
